#!/usr/bin/env Python
# _*_coding:utf-8_*_

from socket import *
import time
import binascii
import tkinter
import threading

def get_time_stamp():
    ct = time.time()
    local_time = time.localtime(ct)
    #data_head = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
    data_head = time.strftime("%H:%M:%S", local_time) #只要时间，不要日期
    data_secs = (ct - int(ct)) * 1000
    time_stamp = "%s.%03d" % (data_head, data_secs)
    return time_stamp

def clickMe():   # 当acction被点击时,该函数则生效
    global flag_stop
    print("udpsever关闭")
    flag_stop=True
    udpServer.shutdown(SHUT_RDWR)   #关闭操作
    udpServer.close()          #关闭连接
    print("udpsever退出")
    p.join()                   #停止线程
    win.destroy()              #退出程序
    pass

def sendto_z21():
    tx1=e1.get().replace(',','')
    udpServer.sendto(bytearray.fromhex(tx1),('192.168.0.111',21106))
    pass

def sendto_app():
    tx2=e2.get().replace(' ','')
    print(tx2)
    udpServer.sendto(bytearray.fromhex(tx2),('192.168.100.2',21105))
    pass

udpServer = socket(AF_INET,SOCK_DGRAM)
def udp_sever( threadName):
    global flag_stop
    print("udpsever打开")
    host = '' #监听所有的ip
    port = 21105 #接口必须一致
    bufsize = 1024
    addr = (host,port)
    logline=''

    udpServer.bind(addr) #开始监听
    udpServer.settimeout(5)     #2秒超时

    while True:
        try:
            data,addr = udpServer.recvfrom(bufsize)  #接收数据和返回地址
        except Exception  as err:
            print ('Exception: ', err)
            if flag_stop==True:
                break
        else:
            log_file = open("./message.log", "a")
            data_str_list=['%02x'%c for c in data] #将bytes转化为两位宽度的strlist
            logline=get_time_stamp()+'\t'+str(addr)+'\t'+' '.join(data_str_list)+'\n'
            log_file.write(logline)
            print(logline)
            log_file.close()
            if addr[0]=='192.168.0.111':
                udpServer.sendto(data,('192.168.100.2',21105))
            if addr[0]=='192.168.100.2':
                udpServer.sendto(data,('192.168.0.111',21106))
        #处理数据
        #print('接收到来自%s的数据%s'%(addr,data));

        #发送数据
       # udpServer.sendto(data,('192.168.0.111',21105))

        #print('...recevied from and return to :',('192.168.0.111',21106))



p=threading.Thread(target=udp_sever,args=(1,))
win = tkinter.Tk()
e1 = tkinter.Entry(win)
flag_stop=False
e2 = tkinter.Entry(win)

def main():
    win.title("Python GUI")    # 添加标题

    toz21 = tkinter.Button(win, text="发送到z21", command=sendto_z21)     # 创建一个按钮, text：显示按钮上面显示的文字, command：当这个按钮被点击之后会调用command函数
    toz21.grid(row=1, column=1)

    tozapp = tkinter.Button(win, text="发送到app", command=sendto_app)     # 创建一个按钮, text：显示按钮上面显示的文字, command：当这个按钮被点击之后会调用command函数
    tozapp.grid(row=2, column=1)

    app_exit = tkinter.Button(win, text="退出!", command=clickMe)     # 创建一个按钮, text：显示按钮上面显示的文字, command：当这个按钮被点击之后会调用command函数
    app_exit.grid(row=0, column=0)

    #tkinter.Label(win, text="报文").grid(row=2)
    e1.grid(row=1,column=0)
    e2.grid(row=2,column=0)

    p.start()

    # 进入消息循环
    win.mainloop()

    pass

if __name__ == '__main__':
    main()